package customer.dao;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import customer.domain.Customer;
import customer.util.DatabaseManager;


//싱글톤
public class CustomerDAO {
	private static CustomerDAO instance = new CustomerDAO();
	private DatabaseManager dbManager = null;//생성자에 객체 대입
	
	private CustomerDAO(){
		
		dbManager = DatabaseManager.getInstance();
		//DatabaseManager 객체 생성
	}
	//싱글톤 디자인
	public static CustomerDAO getInstance(){
		return instance;
	}
	
	//CustomerDB에 고객을 등록시켜주는 메소드 구현
	public int insertCustomer(Customer customer)throws SQLException{
		String sql = "insert into customer values(?,?,?,?,?)";
		
		Connection conn = null;
		PreparedStatement pstmt = null;
		
		try{			
			conn = dbManager.getConnection();
			pstmt = conn.prepareStatement(sql);
			  
			pstmt.setString(1, customer.getResidentNumber());
			pstmt.setString(2, customer.getName());
			pstmt.setString(3, customer.getAddress());
			pstmt.setString(4, customer.getPhoneNumber());
			pstmt.setInt(5, customer.getSalary());
			
			return pstmt.executeUpdate();
 
		}finally{
			dbManager.close(conn, pstmt);
		}
				
	}
	public Customer selectCustomerByResidentNumber(String residentNumber) throws SQLException{
		String sql = "select * from customer where resident_number = ?";
		
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rset = null;
		Customer cus = null;
		
		try{			
			conn = dbManager.getConnection();
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, residentNumber);
			rset = pstmt.executeQuery();
			
			if(rset.next()){
				cus = new Customer(rset.getString(1),rset.getString(2),rset.getString(3),rset.getString(4),rset.getInt(5));
			}
			return cus;

		}finally{
			dbManager.close(conn, pstmt, rset);
		}
	}
	
	public int updateCustomer(Customer cus ) throws SQLException{
		String sql = "update customer set name =?, address = ?, phone_number =? salary=? where resident_number =? ";
		Connection conn = null;
		PreparedStatement pstmt = null;
		
		try{
			conn = dbManager.getConnection();
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,  cus.getName());
			pstmt.setString(2, cus.getAddress());
			pstmt.setString(3, cus.getPhoneNumber());
			pstmt.setInt(4, cus.getSalary());
			pstmt.setString(5, cus.getResidentNumber());
			
			return pstmt.executeUpdate();
			
		}finally{
			dbManager.close(conn, pstmt);
		}
	}
}
